#include "orderingpanel.h"
#include "DarkFoodCard.h"       // Include the product card widget
#include "shoppingcartdialog.h" // Include the shopping cart dialog
#include <QScrollArea>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel> // Potentially for status messages
#include <QMessageBox>
#include <QDebug> // For debugging output

// Include C backend headers
extern "C" {
#include "../backend/drink.h"
#include "../backend/order.h" // Needed for placing order later
}

OrderingPanel::OrderingPanel(int userId, QWidget *parent) :
    QWidget(parent),
    m_userId(userId),
    m_drinkListHead(nullptr)
{
    setupUi();
    loadProducts(); // Load products initially
}

OrderingPanel::~OrderingPanel()
{
    // Free the cached drink list if it exists
    if (m_drinkListHead) {
        free_all_drinks(m_drinkListHead);
    }
    // Qt handles child widget deletion
}

void OrderingPanel::setupUi()
{
    // Main layout for this panel
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(5, 5, 5, 5); // Reduce margins
    mainLayout->setSpacing(5);

    // Top bar for buttons
    QHBoxLayout *topBarLayout = new QHBoxLayout();
    refreshButton = new QPushButton("🔄 刷新商品");
    viewCartButton = new QPushButton("🛒 查看购物车 (0)"); // Show item count
    topBarLayout->addWidget(refreshButton);
    topBarLayout->addStretch();
    topBarLayout->addWidget(viewCartButton);
    mainLayout->addLayout(topBarLayout);

    // Scroll Area for product cards
    scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true); // Important for layout to work correctly
    scrollArea->setObjectName("productScrollArea"); // For potential styling
    scrollArea->setStyleSheet("QScrollArea#productScrollArea { border: none; }"); // Remove border

    // Widget inside Scroll Area
    scrollWidget = new QWidget();
    scrollWidget->setObjectName("productScrollWidget");

    // Layout for the widget inside Scroll Area
    productLayout = new QVBoxLayout(scrollWidget);
    productLayout->setContentsMargins(10, 10, 10, 10); // Add some margin around the content
    productLayout->setSpacing(8); // Reduce spacing between cards (was 10)
    productLayout->addStretch(); // Push cards to the top

    scrollWidget->setLayout(productLayout);
    scrollArea->setWidget(scrollWidget);

    mainLayout->addWidget(scrollArea, 1); // Scroll area takes most space

    // Connections
    connect(refreshButton, &QPushButton::clicked, this, &OrderingPanel::loadProducts);
    connect(viewCartButton, &QPushButton::clicked, this, &OrderingPanel::openShoppingCart);
}

void OrderingPanel::clearProductLayout()
{
    QLayoutItem* item;
    // Remove items from layout AND delete the widget
    while ((item = productLayout->takeAt(0)) != nullptr) {
        if (item->widget()) {
            item->widget()->deleteLater();
        }
        delete item;
    }
     // Re-add the stretch after clearing
     productLayout->addStretch();
}

void OrderingPanel::loadProducts()
{
    qDebug() << "OrderingPanel: Loading products...";
    clearProductLayout();

    // Free previous list if exists
    if (m_drinkListHead) {
        free_all_drinks(m_drinkListHead);
        m_drinkListHead = nullptr;
    }

    // Load drinks from backend
    int drinkCount = load_drinks("drinks.dat", &m_drinkListHead);
    qDebug() << "Loaded" << drinkCount << "drinks from backend.";

    if (drinkCount < 0) {
        QMessageBox::critical(this, "加载错误", "无法加载饮品数据文件！");
        return;
    }
    if (drinkCount == 0) {
         QLabel* emptyLabel = new QLabel("暂无商品可供选择。");
         emptyLabel->setAlignment(Qt::AlignCenter);
         productLayout->insertWidget(0, emptyLabel); // Insert at the top before stretch
         return;
    }

    // Populate layout with DarkFoodCard widgets
    DrinkNode* current = m_drinkListHead;
    int cardIndex = 0;
    while (current != nullptr) {
        DarkFoodCard *card = new DarkFoodCard(this); // Create card
        // TODO: Need a way to set image path in DarkFoodCard if applicable
        card->setDrinkDetails(QString::fromUtf8(current->data.name),
                              QString::fromUtf8(current->data.category), // Assuming category is needed
                              current->data.price,
                              current->data.id); // Pass ID to the card

        // Connect the card's signal to our slot
        // IMPORTANT: Assumes DarkFoodCard has an 'addToCartClicked(int drinkId, int quantity)' signal
        // and potentially a way to get the quantity (e.g., a spinbox inside the card)
        connect(card, &DarkFoodCard::addToCartClicked, this, &OrderingPanel::handleAddToCart);

        productLayout->insertWidget(cardIndex++, card); // Insert before the stretch

        current = current->next;
    }
     qDebug() << "Finished populating cards.";
     // Note: m_drinkListHead is kept for potential use in handleAddToCart/openShoppingCart
     // It should be freed when the panel is destroyed or reloaded.
}

void OrderingPanel::handleAddToCart(int drinkId, int quantity)
{
    qDebug() << "Add to cart requested: Drink ID" << drinkId << "Quantity" << quantity;
    if (quantity <= 0) return; // Ignore zero or negative quantity

    // Update cart map
    m_cartItems[drinkId] = m_cartItems.value(drinkId, 0) + quantity; // Add to existing or set new

    // Update cart button text
    int totalItems = 0;
    for(int count : m_cartItems.values()) {
        totalItems += count;
    }
    viewCartButton->setText(QString("🛒 查看购物车 (%1)").arg(totalItems));

    // Optional: Provide feedback to user (e.g., status bar message)
    // statusBar()->showMessage(QString("已将 %1 添加到购物车").arg(drinkName), 2000);
}

void OrderingPanel::openShoppingCart()
{
    qDebug() << "Opening shopping cart with items:" << m_cartItems;
    if (m_cartItems.isEmpty()) {
        QMessageBox::information(this, "购物车", "购物车是空的！");
        return;
    }

    // Create and show the shopping cart dialog
    // Pass necessary data: cart items, user ID, and potentially the drink list for details
    ShoppingCartDialog *cartDialog = new ShoppingCartDialog(m_cartItems, m_userId, m_drinkListHead, this);
    cartDialog->setAttribute(Qt::WA_DeleteOnClose); // Ensure it's deleted after closing

    // Connect the orderPlacedSuccessfully signal to clear the cart and refresh
    connect(cartDialog, &ShoppingCartDialog::orderPlacedSuccessfully, this, [this]() {
        m_cartItems.clear(); // Clear the local cart map
        viewCartButton->setText("🛒 查看购物车 (0)"); // Reset button text
        // Reload products because stock has changed
        // Note: This re-fetches from drinks.dat, which should have been updated by the dialog
        loadProducts();
    });

    cartDialog->exec(); // Show as modal dialog
}